using System;
using System.Collections.Generic;
using System.Text;

namespace Avanzis.Helpers.PersistentObjects
{
    /// <summary>
    /// Base <see cref="IThreadScopeInfo"/> implementation. It's up 
    /// to derived classes to provide a correct implementation 
    /// of <c>CurrentStack</c> only
    /// </summary>
    public abstract class AbstractThreadScopeInfo : IThreadScopeInfo
    {
        public abstract Stack<ISessionScope> CurrentStack { get; }

        public void RegisterScope(ISessionScope scope)
        {
            CurrentStack.Push(scope);
        }

        public ISessionScope GetRegisteredScope()
        {
            Stack<ISessionScope> stack = CurrentStack;

            if (stack.Count == 0)
            {
                return null;
            }
            else
            {
                return stack.Peek() as ISessionScope;
            }
        }

        public void UnRegisterScope(ISessionScope scope)
        {
            if (GetRegisteredScope() != scope)
            {
                throw new PersistentObjectsException("Tried to unregister a scope that is not the active one");
            }

            CurrentStack.Pop();
        }

        public bool HasInitializedScope
        {
            get { return GetRegisteredScope() != null; }
        }
    }
}
